package org.example.ims.Controller.Base;

import org.example.ims.DTO.Response;
import org.example.ims.Entity.Base.Supplier;
import org.example.ims.Service.Base.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    // 根据ID查询供货商
    @GetMapping("/{id}")
    public ResponseEntity<Response<Supplier>> getSupplierById(@PathVariable Integer id) {
        Optional<Supplier> supplier = supplierService.getSupplierById(id);
        if (supplier.isPresent()) {
            return ResponseEntity.ok(Response.success(supplier.get()));
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND)
                .body(Response.error("NOT_FOUND", "供货商（ID：" + id + "）未找到"));
    }

    // 查询所有供货商（带分页）
    @GetMapping("/search")
    public Response<Page<Supplier>> getAllSuppliers(
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(supplierService.getAllSuppliers(page, size));
    }

    @GetMapping
    public Response<Page<Supplier>> searchSuppliers(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String contact,
            @RequestParam(required = false) String phone,
            @RequestParam(defaultValue = "0") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {
        return Response.success(supplierService.searchSuppliers(name, contact, phone, page, size));
    }


    // 创建供货商
    @PostMapping
    public ResponseEntity<Supplier> createSupplier(@RequestBody Supplier supplier) {
        Supplier savedSupplier = supplierService.createSupplier(supplier);
        return ResponseEntity.ok(savedSupplier);
    }

    // 更新供货商信息
    @PutMapping("/{id}")
    public ResponseEntity<Supplier> updateSupplier(@PathVariable Integer id, @RequestBody Supplier supplierDetails) {
        Supplier updatedSupplier = supplierService.updateSupplier(id, supplierDetails);
        if (updatedSupplier != null) {
            return ResponseEntity.ok(updatedSupplier);
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
    }

    // 删除供货商
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteSupplier(@PathVariable Integer id) {
        supplierService.deleteSupplier(id);
        return ResponseEntity.ok().build();
    }
}